<?php

namespace App\Http\Controllers;
use App\Models\User;
use App\Service\HttpService;
use App\Service\UsersService;
use App\Traits\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\Service\MiniProgramService;
class AuthController extends Controller
{

    use JsonResponse;
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        //$this->middleware('auth:api', ['except' => ['login']]);
    }

    /**
     * Get a JWT via given credentials.
     *
     * @param MiniProgramService $miniProgramService
     * @param HttpService $httpService
     * @return false|string
     */
    public function logins(MiniProgramService $miniProgramService,HttpService $httpService,UsersService $usersService,User $user)
    {
        $code = request(['code']);
        $avatar = request('avatar');
        $nickname = request('nickname');
        if(!$code){
            return tips(-1,'error','参数错误');
        }

        try {
            $data = $miniProgramService->getOpenID($code['code'],$httpService);
        } catch (\Exception $e) {
            return $this->errorReturn(10001, $e->getMessage());
        }

        $iv = request(['iv']);
        $encryptedData = request(['encryptedData']);
        //Log::debug('getMiniProgramMobile------：'.json_encode(['iv'=>$iv,'encryptedData'=>$encryptedData,'code'=>$code]));
        $openid = isset($data['openid']) ? $data['openid'] : '';
        if (!$openid) {
            return tips(-1,'error', '获取openid失败...');
        }

        try {
            $errCode = $miniProgramService->decryptData($data['session_key'],$encryptedData['encryptedData'], $iv['iv'],  $decryptData);
        } catch (\Exception $e) {
            return tips(-1,'error',$e->getMessage());
        }

        $decryptData = json_decode($decryptData,true);
        if ($errCode == 0) {
            // 返回的数据
            $decryptData['session_key'] = $data['session_key'];
            $decryptData['openid'] = $data['openid'];

            $datas['mobile'] = $decryptData['phoneNumber'];
            $datas['avatar'] = $avatar;
            $datas['name'] = $nickname;
            $user = $usersService->getUsers($datas['mobile']);
            if($user){

                $user->where('mobile',$datas['mobile'])->update($datas);

            }
            return tips(1,'success',$decryptData);
        }else{
            return tips(-1,'error',$errCode);
        }
    }



    public function login(MiniProgramService $miniProgramService,HttpService $httpService,UsersService $usersService,User $users)
    {
        //$code = request(['code']);
        $avatar = request('avatar');
        $nickname = request('nickname');

        $mobile = request('mobile');
        $datas['mobile'] = $mobile;
        $datas['avatar'] = $avatar;
        $datas['name'] = $nickname;
        $user = $usersService->getUsers($datas['mobile']);
        if($user){

            $users->where('mobile',$datas['mobile'])->update($datas);

        }
        return tips(1,'success','成功');

    }



    /**
     *
     * @param MiniProgramService $miniProgramService
     * @param HttpService $httpService
     * @author Bryant
     * @date 2020-10-28 16:27
     *
     *
     获取 session_key
     */
    public function getCode(MiniProgramService $miniProgramService,HttpService $httpService)
    {
        $code = request(['code']);
        if(!$code){
            return tips(-1,'error','参数错误');
        }

        try {
            $data = $miniProgramService->getOpenID($code['code'],$httpService);
        } catch (\Exception $e) {
            return $this->errorReturn(10001, $e->getMessage());
        }

        return tips(1,'success',$data);
    }

    /**
     * 获取token
    */
    public function get_token(){
        $mobile = request(['mobile']);

        // 登陆
        $input['mobile'] = $mobile;
        if (!$token = Auth::guard('api')->attempt($input)) {
            return tips(1,'success', '');
        }

        return tips(1,'success',$token);
    }
    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        return response()->json(auth()->user());
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth()->logout();

        return response()->json(['message' => 'Successfully logged out']);
    }

    /**
     * Refresh a token.
     *
     * @return false|string
     */
    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param string $token
     *
     * @return false|string
     */
    protected function respondWithToken($token)
    {
        return tips('success',$token);
        //return response()->json([
        //    'access_token' => $token,
        //    'token_type' => 'bearer',
        //    'expires_in' => auth()->factory()->getTTL() * 600000000
        //]);
    }
}
